/**
 * 权限控制组件
 */

import React, { useState, useEffect } from 'react';
import { hasPermission, hasAnyPermission, hasAllPermissions, hasRole } from '@/utils/permissions';

// 权限控制组件的Props接口
interface PermissionControlProps {
  children: React.ReactNode;
  permission?: string;
  permissions?: string[];
  role?: string;
  requireAll?: boolean; // 是否需要所有权限，默认false（任一权限即可）
  fallback?: React.ReactNode; // 无权限时显示的内容
  loading?: React.ReactNode; // 权限检查中显示的内容
}

/**
 * 权限控制组件
 * 
 * 用法示例：
 * <PermissionControl permission="auth.view_user">
 *   <Button>查看用户</Button>
 * </PermissionControl>
 * 
 * <PermissionControl permissions={["auth.add_user", "auth.change_user"]} requireAll={false}>
 *   <Button>用户管理</Button>
 * </PermissionControl>
 */
export const PermissionControl: React.FC<PermissionControlProps> = ({
  children,
  permission,
  permissions,
  role,
  requireAll = false,
  fallback = null,
  loading = null,
}) => {
  const [hasAccess, setHasAccess] = useState<boolean | null>(null);

  useEffect(() => {
    const checkPermission = async () => {
      try {
        let result = false;

        if (role) {
          // 检查角色
          result = await hasRole(role);
        } else if (permission) {
          // 检查单个权限
          result = await hasPermission(permission);
        } else if (permissions && permissions.length > 0) {
          // 检查多个权限
          if (requireAll) {
            result = await hasAllPermissions(permissions);
          } else {
            result = await hasAnyPermission(permissions);
          }
        } else {
          // 没有指定权限要求，默认允许
          result = true;
        }

        setHasAccess(result);
      } catch (error) {
        console.error('权限检查失败:', error);
        setHasAccess(false);
      }
    };

    checkPermission();
  }, [permission, permissions, role, requireAll]);

  // 权限检查中
  if (hasAccess === null) {
    return <>{loading}</>;
  }

  // 有权限
  if (hasAccess) {
    return <>{children}</>;
  }

  // 无权限
  return <>{fallback}</>;
};

// 权限控制Hook
export const usePermission = () => {
  return {
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole,
  };
};

// 权限检查Hook - 返回权限状态
export const usePermissionCheck = (
  permission?: string,
  permissions?: string[],
  role?: string,
  requireAll: boolean = false
) => {
  const [hasAccess, setHasAccess] = useState<boolean | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const checkPermission = async () => {
      setLoading(true);
      try {
        let result = false;

        if (role) {
          result = await hasRole(role);
        } else if (permission) {
          result = await hasPermission(permission);
        } else if (permissions && permissions.length > 0) {
          if (requireAll) {
            result = await hasAllPermissions(permissions);
          } else {
            result = await hasAnyPermission(permissions);
          }
        } else {
          result = true;
        }

        setHasAccess(result);
      } catch (error) {
        console.error('权限检查失败:', error);
        setHasAccess(false);
      } finally {
        setLoading(false);
      }
    };

    checkPermission();
  }, [permission, permissions, role, requireAll]);

  return { hasAccess, loading };
};

// 高阶组件：权限控制
export const withPermission = <P extends object>(
  Component: React.ComponentType<P>,
  permission?: string,
  permissions?: string[],
  role?: string,
  requireAll: boolean = false,
  fallback?: React.ReactNode
) => {
  return (props: P) => (
    <PermissionControl
      permission={permission}
      permissions={permissions}
      role={role}
      requireAll={requireAll}
      fallback={fallback}
    >
      <Component {...props} />
    </PermissionControl>
  );
};

// 权限按钮组件
interface PermissionButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  permission?: string;
  permissions?: string[];
  role?: string;
  requireAll?: boolean;
  children: React.ReactNode;
}

export const PermissionButton: React.FC<PermissionButtonProps> = ({
  permission,
  permissions,
  role,
  requireAll = false,
  children,
  ...buttonProps
}) => {
  const { hasAccess, loading } = usePermissionCheck(permission, permissions, role, requireAll);

  if (loading) {
    return <button {...buttonProps} disabled>加载中...</button>;
  }

  if (!hasAccess) {
    return null;
  }

  return <button {...buttonProps}>{children}</button>;
};

export default PermissionControl;
